{% extends 'base.html' %}
{% load static %}

{% block title %}{{ page_title|default:"活动地图 - 本地有约" }}{% endblock %}

{% block content %}
<div class="container-fluid py-4">
    <div class="row mb-4">
        <div class="col">
            <h1 class="h3 mb-1">活动地图</h1>
            <p class="text-muted mb-0">在地图上查看所有活动的位置</p>
        </div>
        <div class="col-auto">
            <a href="{% url 'location:activity_list' %}" class="btn btn-outline-primary">
                <i class="fas fa-list"></i> 列表视图
            </a>
            <button class="btn btn-outline-success ms-2" onclick="getUserLocation()">
                <i class="fas fa-location-arrow"></i> 定位到我
            </button>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <div id="full-map-container" style="height: 70vh; border-radius: 8px; overflow: hidden; border: 1px solid #dee2e6;"></div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_css %}
<style>
.map-marker-popup {
    max-width: 250px;
    padding: 12px;
}

.map-marker-popup h6 {
    font-size: 14px;
    font-weight: 600;
    margin-bottom: 8px;
    color: #333;
}

.map-marker-popup p {
    margin-bottom: 4px;
    font-size: 12px;
    color: #666;
}

.map-marker-popup .badge {
    font-size: 11px;
}
</style>
{% endblock %}

{% block scripts %}
<!-- 引入百度地图API -->
<script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=rUiyl00fneDC8rieZJagiXxwyDl7ZYje"></script>

<script>
let fullMap = null;
let userLocation = null;

// 初始化完整地图
function initFullMap() {
    try {
        fullMap = new BMap.Map("full-map-container");
        const point = new BMap.Point(116.404, 39.915); // 默认北京
        fullMap.centerAndZoom(point, 12);
        fullMap.enableScrollWheelZoom(true);

        // 添加基本控件
        fullMap.addControl(new BMap.NavigationControl());
        fullMap.addControl(new BMap.ScaleControl());
        fullMap.addControl(new BMap.MapTypeControl());

        // 添加活动标记
        const eventsData = {{ events_json|safe }};
        addActivityMarkers(eventsData);

        console.log('完整地图初始化成功，加载了 ' + eventsData.length + ' 个活动');

    } catch (error) {
        console.error('地图初始化失败:', error);
        showToast('地图初始化失败，请刷新页面重试', 'error');
    }
}

// 添加活动标记到地图
function addActivityMarkers(activities) {
    if (!fullMap || !activities || activities.length === 0) {
        console.log('没有活动数据可显示');
        return;
    }

    activities.forEach(activity => {
        if (!activity.latitude || !activity.longitude) {
            console.warn('活动缺少位置信息:', activity.title);
            return;
        }

        const point = new BMap.Point(activity.longitude, activity.latitude);
        const marker = new BMap.Marker(point);

        // 创建信息窗口内容
        const content = `
            <div class="map-marker-popup">
                <h6>${escapeHtml(activity.title)}</h6>
                <p class="mb-1"><small><i class="fas fa-map-marker-alt"></i> ${escapeHtml(activity.location || '地址未提供')}</small></p>
                <p class="mb-1"><small><i class="fas fa-clock"></i> ${activity.start_time}</small></p>
                <p class="mb-1"><small><i class="fas fa-tag"></i> ${escapeHtml(activity.category)}</small></p>
                <div class="d-flex justify-content-between align-items-center mt-2">
                    <span class="badge ${activity.is_free ? 'bg-success' : 'bg-warning'}">
                        ${activity.is_free ? '免费' : '¥' + activity.fee}
                    </span>
                    <span class="badge bg-primary">
                        ${activity.current_participants || 0}/${activity.max_participants}人
                    </span>
                </div>
                <button class="btn btn-sm btn-primary w-100 mt-2" onclick="viewActivityDetail(${activity.id})">
                    <i class="fas fa-info-circle"></i> 查看详情
                </button>
            </div>
        `;

        const infoWindow = new BMap.InfoWindow(content, {
            width: 250,
            height: 220
        });

        marker.addEventListener("click", function() {
            this.openInfoWindow(infoWindow);
        });

        fullMap.addOverlay(marker);
    });
}

// 获取用户位置
function getUserLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            function(position) {
                const lat = position.coords.latitude;
                const lng = position.coords.longitude;
                userLocation = { lat, lng };

                // 更新地图中心
                const point = new BMap.Point(lng, lat);
                fullMap.centerAndZoom(point, 15);

                // 添加用户位置标记
                addUserLocationMarker();

                showToast('位置获取成功！', 'success');
            },
            function(error) {
                console.error('获取位置失败:', error);
                let message = '获取位置失败';
                switch(error.code) {
                    case error.PERMISSION_DENIED:
                        message = '位置访问被拒绝，请在浏览器设置中允许位置访问';
                        break;
                    case error.POSITION_UNAVAILABLE:
                        message = '位置信息不可用';
                        break;
                    case error.TIMEOUT:
                        message = '位置请求超时';
                        break;
                }
                showToast(message, 'error');
            }
        );
    } else {
        showToast('浏览器不支持地理位置服务', 'error');
    }
}

// 添加用户位置标记
function addUserLocationMarker() {
    if (!userLocation || !fullMap) return;

    // 清除之前的用户位置标记
    fullMap.clearOverlays();

    const point = new BMap.Point(userLocation.lng, userLocation.lat);
    const marker = new BMap.Marker(point);

    // 重新添加活动标记
    const eventsData = {{ events_json|safe }};
    addActivityMarkers(eventsData);

    // 添加用户位置标记（蓝色）
    const userMarker = new BMap.Marker(point, {
        icon: new BMap.Icon('http://api.map.baidu.com/images/spot_point.png', new BMap.Size(24, 24))
    });
    fullMap.addOverlay(userMarker);
}

// 查看活动详情
function viewActivityDetail(activityId) {
    if (activityId) {
        window.location.href = `/location/activity_detail/${activityId}/`;
    } else {
        showToast('活动ID无效', 'error');
    }
}

// HTML 转义函数
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 显示提示信息
function showToast(message, type = 'info') {
    // 简单的提示实现，您可以使用更完整的 toast 系统
    alert(message);
}

// 页面加载完成后初始化地图
document.addEventListener('DOMContentLoaded', function() {
    console.log('完整地图页面初始化开始...');
    setTimeout(() => {
        initFullMap();
    }, 100);
});
</script>
{% endblock %}